<template>
  <div class="go-tables-rank" :style="`color: ${state.mergedConfig.textColor}`">
    <div
        class="row-item"
        v-for="(item, i) in state.rows"
        :key="item.toString() + item.scroll"
        :style="`height: ${state.heights[i]}px;`"
    >
      <div class="ranking-info">
        <div class="rank" :style="`color: ${state.mergedConfig.color};font-size: ${state.mergedConfig.indexFontSize}px`">No.{{ item.ranking }}</div>
        <div class="info-name" :style="`font-size: ${state.mergedConfig.leftFontSize}px`" v-html="item.name" />
        <div class="ranking-value" :style="`color: ${state.mergedConfig.textColor};font-size: ${state.mergedConfig.rightFontSize}px`">
          {{
            typeof state.mergedConfig.valueFormatter === 'function'
                ? state.mergedConfig.valueFormatter(item)
                : item.value
          }}
          {{ state.mergedConfig.unit }}
        </div>
      </div>
      <div class="ranking-column" :style="`border-color: ${state.mergedConfig.borderColor}`">
        <div class="inside-column" :style="`width: ${item.percent}%;background-color: ${state.mergedConfig.color}`">
          <div class="shine" />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import {onMounted, defineProps, onUnmounted, reactive, watch, computed} from "vue";
import {copyDefinedProperties} from "../../../utils/copy.ts"
import {getColorFromLocal} from "../../../package/style/css.ts";
defineOptions({
  name: 'Table'
})
const props = defineProps(['option']);
const left=computed(()=>`${(state.mergedConfig.left/100)*state.window.width}px`)
const top=computed(()=>`${(state.mergedConfig.top/100)*state.window.height}px`)
const height=computed(()=>`${(state.mergedConfig.height/100)*state.window.height}px`)
const width=computed(()=>`${(state.mergedConfig.width/100)*state.window.width}px`)
let cmap=getColorFromLocal()
const state = reactive({
  mergedConfig: {  // 数据
    dataset: [
      { "name": "荣成", "value": 26700 },
      { "name": "河南", "value": 20700 },
      { "name": "河北", "value": 18700 },
      { "name": "徐州", "value": 17800 },
      { "name": "漯河", "value": 16756 },
      { "name": "三门峡", "value": 12343 },
      { "name": "郑州", "value": 9822 },
      { "name": "周口", "value": 8912 },
      { "name": "濮阳", "value": 6834 },
      { "name": "信阳", "value": 5875 },
      { "name": "新乡", "value": 3832 },
      { "name": "大同", "value": 1811 }
    ],
    // 表行数
    rowNum: 5,
    // 轮播时间
    waitTime: 2,
    // 数值单位
    unit: '',
    // 自动排序
    sort: true,
    color: cmap.color[0],
    textColor: cmap.textColor,
    borderColor: cmap.borderColor,
    carousel: 'single',
    //序号字体大小
    indexFontSize: 12,
    //左侧数据字体大小
    leftFontSize: 12,
    //右侧数据字体大小
    rightFontSize: 12,
    // 格式化
    valueFormatter(item: { value: any}) { return item.value},
    height:100,
    width:100,
    left:10,
    top:10,
  },
  rowsData: [],
  rows: [
    {
      scroll: 0,
      ranking: 1,
      name: '',
      value: '',
      percent: 0
    }
  ],
  heights: [0],
  animationIndex: 0,
  animationHandler: 0,
  updater: 0,
  avgHeight: 0,
  window:{
    height:1700,
    width:800,
  },
})
onMounted(()=>{
  setting()
  onRestart()
})
function setting(){
  if(props.option!==undefined){
    // console.log(props.option)
    copyDefinedProperties(props.option,state.mergedConfig)
    state.window={
      width: document.body.clientWidth,
      height: document.body.clientHeight
    }
  }
}
const calcRowsData = () => {
  let { dataset, rowNum, sort } = state.mergedConfig
  // @ts-ignore
  sort &&
  dataset.sort(({ value: a }, { value: b }) => {
    if (a > b) return -1
    if (a < b) return 1
    if (a === b) return 0
  })
  // @ts-ignore
  const value = dataset.map(({ value }) => value)
  const min = Math.min(...value) || 0
  // abs of min
  const minAbs = Math.abs(min)
  const max = Math.max(...value) || 0
  // abs of max
  const maxAbs = Math.abs(max)
  const total = max + minAbs
  dataset = dataset.map((row: any, i: number) => ({
    ...row,
    ranking: i + 1,
    percent: ((row.value + minAbs) / total) * 100
  }))
  const rowLength = dataset.length
  if (rowLength > rowNum && rowLength < 2 * rowNum) {
    dataset = [...dataset, ...dataset]
  }
  dataset = dataset.map((d: any, i: number) => ({ ...d, scroll: i }))
  state.rowsData = dataset
  state.rows = dataset
}

const calcHeights = (onresize = false) => {
  const { rowNum, dataset } = state.mergedConfig
  // console.log(state.mergedConfig.height)
  const avgHeight = (state.mergedConfig.height/100)*state.window.height/ rowNum
  state.avgHeight = avgHeight

  if (!onresize) state.heights = new Array(dataset.length).fill(avgHeight)
}

const animation = async (start = false) => {
  let { avgHeight, animationIndex, mergedConfig, rowsData, updater } = state
  const { waitTime, carousel, rowNum } = mergedConfig
  const rowLength = rowsData.length
  if (rowNum >= rowLength) return
  if (start) {
    await new Promise(resolve => setTimeout(resolve, waitTime))
    if (updater !== state.updater) return
  }
  const animationNum = carousel === 'single' ? 1 : rowNum
  let rows = rowsData.slice(animationIndex)
  rows.push(...rowsData.slice(0, animationIndex))
  state.rows = rows.slice(0, rowNum + 1)
  state.heights = new Array(rowLength).fill(avgHeight)
  // console.log(state.heights)
  await new Promise(resolve => setTimeout(resolve, 300))
  if (updater !== state.updater) return
  state.heights.splice(0, animationNum, ...new Array(animationNum).fill(0))
  animationIndex += animationNum
  const back = animationIndex - rowLength
  if (back >= 0) animationIndex = back

  state.animationIndex = animationIndex
  state.animationHandler = setTimeout(animation, waitTime * 1000 - 300) as any
}

const stopAnimation = () => {
  state.updater = (state.updater + 1) % 999999
  if (!state.animationHandler) return
  clearTimeout(state.animationHandler)
}

const onRestart = async () => {
  try {
    if (!state.mergedConfig) return
    let { dataset, rowNum, sort } = state.mergedConfig
    stopAnimation()
    calcRowsData()
    let flag = true
    if (dataset.length <= rowNum) {
      flag = false
    }
    calcHeights(flag)
    animation(flag)
  } catch (error) {
    console.error(error)
  }
}



// watch(
//     () => w.value,
//     () => {
//       onRestart()
//     }
// )
//
// watch(
//     () => h.value,
//     () => {
//       onRestart()
//     }
// )

// watch(
//     () => rowNum.value,
//     () => {
//       onRestart()
//     }
// )
//
// // 数据更新（配置时触发）
// watch(
//     () => props.chartConfig.option.dataset,
//     () => {
//       onRestart()
//     },
//     {
//       deep: false
//     }
// )

// 数据callback处理（预览时触发）
// useChartDataFetch(props.chartConfig, useChartEditStore, (resData: any[]) => {
//   props.chartConfig.option.dataset = resData
//   onRestart()
// })
function SetOption(data){
  state.mergedConfig.dataset=data
  onRestart()
}
onUnmounted(() => {
  stopAnimation()
})
window.addEventListener('resize',()=>{
  // console.log("width,height",document.body.clientWidth,document.body.clientHeight)
  state.window={
    width: document.body.clientWidth,
    height: document.body.clientHeight
  }
  onRestart()
})
defineExpose({SetOption})
</script>

<style scoped>
.go-tables-rank {
  position: absolute;
  left:v-bind(left);
  top:v-bind(top);
  width: v-bind(width);
  height: v-bind(height);
  //width: 100%;
  //height: 100%;
  overflow: hidden;

  .row-item {
    transition: all 0.3s;
    display: flex;
    flex-direction: column;
    justify-content: center;
    overflow: hidden;
  }

  .ranking-info {
    display: flex;
    width: 100%;
    font-size: 13px;
    align-items: center;

    .rank {
      margin-right: 5px;
    }

    .info-name {
      flex: 1;
    }
  }

  .ranking-column {
    border-bottom: 2px solid #1370fb80;
    margin-top: 5px;

    .inside-column {
      position: relative;
      height: 6px;
      margin-bottom: 2px;
      border-radius: 1px;
      overflow: hidden;
    }

    .shine {
      position: absolute;
      left: 0%;
      top: 2px;
      height: 2px;
      width: 50px;
      transform: translateX(-100%);
      background: radial-gradient(rgb(40, 248, 255) 5%, transparent 80%);
      animation: shine 3s ease-in-out infinite alternate;
    }
  }
}

@keyframes shine {
  80% {
    left: 0;
    transform: translateX(-100%);
  }

  100% {
    left: 100%;
    transform: translateX(0%);
  }
}
</style>
